import { call, put, all, takeLatest } from "redux-saga/effects";
import Router from "next/router";
import { api } from "redux/api";
import { removeCookie } from "redux/api/cookie";
import { Creators as AuthCreators } from "redux/actions/auth";
import { AuthTypes } from "redux/constants";
import interceptResponse from "redux/api/interceptResponse";
import interceptError from "redux/api/interceptError";

function* getLogout() {
  yield call(removeCookie, "access_token");
  yield call(Router.replace, { pathname: "/" });
  yield put(AuthCreators.getLogoutSuccess());
}

function* checkAuth({ payload }) {
  try {
    const { token } = payload;
    yield call(api.setHeader, "Authorization", `Bearer ${token}`);
    const response = yield call(api.get, "/api/needLogin");
    yield interceptResponse(response);

    if (response.data?.code !== 1000) {
      throw response;
    }
    console.log("checkAuth response", response);
    yield put(AuthCreators.getSuccess(response.data));
  } catch (e) {
    yield interceptError(AuthCreators.getFailure, e);
  }
}

export default function* () {
  yield all([
    takeLatest(AuthTypes.GET_LOGOUT_REQUEST, getLogout),
    takeLatest(AuthTypes.CHECK_AUTH, checkAuth),
  ]);
}

// https://www.gravatar.com/avatar/080849c69a42a7c9dbca291677b6d62a.png?f=y&d=identicon&r=g
